import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/b2ctrailer/b2ctrailermodel.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class ReturnsTrailerSubmitScreen extends StatelessWidget {
  TrailerType trailerType;

  ReturnsTrailerSubmitScreen({ this.trailerType});

  @override
  Widget build(BuildContext context) {
    return ReturnsTrailerSubmitScreenPage( trailerType: trailerType);
  }
}

class ReturnsTrailerSubmitScreenPage extends StatefulWidget {
  TrailerType trailerType;

  ReturnsTrailerSubmitScreenPage({ this.trailerType});

  @override
  _ReturnsTrailerSubmitPageState createState() => _ReturnsTrailerSubmitPageState(trailerType: trailerType);
}

class _ReturnsTrailerSubmitPageState extends BaseState<ReturnsTrailerSubmitScreen> {
  TrailerType trailerType;
  PhotoBean bolPhoto;

  String oblpnList = "OBLPN List(0)";
  List<TrailerOBLPN> data = new List();
  List<String> pendingOutboundLpns = new List();

  _ReturnsTrailerSubmitPageState({this.trailerType});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Trailer: Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
      data = trailerType.bindLpns;
      pendingOutboundLpns = trailerType.lpns;
      if (pendingOutboundLpns == null) {
        pendingOutboundLpns = new List();
      }
      bolPhoto = new PhotoBean();
      if(!Utils.isEmpty(trailerType.closeDoorPath)){
        bolPhoto.urlImg = trailerType.closeDoorPath;
      }
      if(data!=null){
        oblpnList = "OBLPN List(${data.length})";
      }
    });
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    bolPhoto.image = image;
    fileUpload(Utils.getStringisEmpty(trailerType.trailerId), "trailer", image, "close", 0, 0, false, false);
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "Trailer#: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.isEmpty(trailerType.trailerName) ? Utils.getStringisEmpty(trailerType.trailerId) : Utils.getStringisEmpty(trailerType.trailerName),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                lpnLoaded(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    // requestPermissions();
                    // Utils.scanBarcode(context);
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      lpnLoaded(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "scan or input outbound lpn",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 1) {
                      return;
                    }
                    setState(() {
                      type = 1;
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      Utils.getStringisEmpty(oblpnList),
                      style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: GestureDetector(
                  onTap: () {
                    // 请求焦点
                    FocusScope.of(context).requestFocus(FocusNode());
                    if (type == 2) {
                      return;
                    }
                    setState(() {
                      type = 2;
                    });
                  },
                  child: Container(
                    padding: EdgeInsets.all(5),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                      borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                      border: Border.all(
                        color: MyAppTheme.nearlyBlue, // 边框颜色
                        width: 0.5, // 边框宽度
                      ),
                    ),
                    child: Text(
                      'Pending OBLPN',
                      style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                    ), // 子控件，如果需要的话
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Visibility(visible: type == 1 ? true : false, child: Expanded(child: setListView())),
          Visibility(visible: type == 2 ? true : false, child: Expanded(child: setPendingListView())),
          SizedBox(
            height: 5,
          ),
          setPhotoView("After Loading:  ", 0, bolPhoto),
          SizedBox(
            height: 5,
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        TrailerOBLPN trailerOBLPN = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                    flex: 1,
                    child: Text(
                      Utils.getStringisEmpty(trailerOBLPN.lpn),
                      style: MyAppTheme.test12,
                    )),
                GestureDetector(
                  onTap: () {
                    showDialog(
                      context: context,
                      builder: (context) => CustomDialog(
                        lpn: trailerOBLPN.lpn,
                        trailer: (Utils.isEmpty(trailerType.trailerName) ? Utils.getStringisEmpty(trailerType.trailerId) : Utils.getStringisEmpty(trailerType.trailerName)),
                      ),
                    ).then((value) => {
                          if ((value != null) && value) {removeLpn(int.parse(trailerOBLPN.id))}
                        });
                    ;
                  },
                  child: Icon(
                    Icons.delete,
                    size: 20,
                    color: MyAppTheme.grey,
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setPendingListView() {
    return ListView.builder(
      shrinkWrap: true,
      // physics: NeverScrollableScrollPhysics(),
      itemCount: pendingOutboundLpns == null ? 0 : pendingOutboundLpns.length,
      itemBuilder: (context, index) {
        String trk = pendingOutboundLpns[index];
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              Utils.getStringisEmpty(trk),
              style: MyAppTheme.test12,
            ),
            Divider(),
          ],
        );
      },
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text(
                  hintText,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                ),
              ],
            ),
          ),
          Expanded(
              flex: 2, //设置权重
              child: Row(
                children: [
                  Container(
                    width: 70,
                    height: 70,
                    child: Stack(
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            // 请求焦点
                            FocusScope.of(context).requestFocus(FocusNode());
                            ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                          },
                          child: photoBean.image == null
                              ? (photoBean.urlImg == null
                                  ? Image.asset(
                                      'assets/images/add.png',
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    )
                                  : Image.network(
                                      Constants.baseImgUrl + photoBean.urlImg,
                                      width: 70,
                                      height: 70,
                                      fit: BoxFit.cover,
                                    ))
                              : Image.file(
                                  photoBean.image,
                                  width: 70,
                                  height: 70,
                                  fit: BoxFit.cover,
                                ),
                        ),
                        Visibility(
                          visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                          child: Positioned(
                            top: 2.0,
                            right: 2.0,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  photoBean.urlImg = null;
                                  photoBean.image = null;
                                });
                              },
                              child: Image.asset(
                                'assets/images/ic_delete_menu.png',
                                width: 15,
                                height: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    flex: 2, //设置权重
                    child: Text(
                      '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                    ),
                  ),
                ],
              )),
        ],
      ),
    );
  }

  void lpnLoaded(String barcode) async {
    updateHint('');
    TrailerIBLPNQr trailerIBLPNQr = new TrailerIBLPNQr();
    trailerIBLPNQr.trailerId = int.parse(trailerType.trailerId);
    List<String> list = new List();
    list.add(barcode);
    trailerIBLPNQr.lpns = list;

    String json = jsonEncode(trailerIBLPNQr);

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnLoaded,method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        textEditingController.text = "";
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TrailerOBLPN.fromJson(userJson)).toList());
        oblpnList = "OBLPN List(${data.length})";
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void removeLpn(int id) async {
    updateHint('');
    RemoveLpn removeLpn = new RemoveLpn();
    removeLpn.id = id;
    removeLpn.trailerId = int.parse(trailerType.trailerId);

    String json = jsonEncode(removeLpn);

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnRemoveLpn,method: BaseMethod.delete, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        textEditingController.text = "";
        data = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => TrailerOBLPN.fromJson(userJson)).toList());
        oblpnList = "OBLPN List(${data.length})";
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }
  void trailerComplete() async {
    updateHint('');
    TrailerQr trailerQr = new TrailerQr();
    trailerQr.trailerId = trailerType.trailerId;
    trailerQr.closeDoor = bolPhoto.urlImg;

    String json = jsonEncode(trailerQr);

    // 显示加载中对话框
    LoadingIndicator.show(context,title: "Submit...");

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.trailerComplete,method: BaseMethod.put, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
        Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    bolPhoto.urlImg = path;
  }

  @override
  void setNext() {
    if ((bolPhoto.image != null) && Utils.isEmpty(bolPhoto.urlImg)) {
      fileUpload(Utils.getStringisEmpty(trailerType.trailerId), "trailer", bolPhoto.image, "close", 0, 0, false, true);
    }
    trailerComplete();
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
      bolPhoto = new PhotoBean();
    });
  }

}

class CustomDialog extends StatefulWidget {
  String lpn;
  String trailer;

  CustomDialog({this.lpn, this.trailer});

  @override
  _CustomDialogState createState() => _CustomDialogState(lpn: lpn, trailer: trailer);
}

class _CustomDialogState extends State<CustomDialog> {
  String lpn;
  String trailer;

  _CustomDialogState({this.lpn, this.trailer});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("Remove ${lpn} form ${trailer}", style: MyAppTheme.textred14),
            SizedBox(height: 16.0),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Close',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                    )),
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Confirm',
                        style: MyAppTheme.title,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
